<template>
	<view>	
		<view @touchstart="onBlur" class="chat-main" ref="scrollDiv">
			<scroll-view 
			:scroll-y="true"
			 @scroll="scroll"
			 :scroll-top="scrollTop"
			style="display: flex;flex-direction: column;flex-wrap: warp;width:100%;height: 100vh;"
			:style="{'padding-bottom': height}"
			>
				<view class="chat-items" v-for="(item, index) in msgList" :key="index" :id="'id-'+index">
					<view>
						<view>
							<view  v-if="item.msg.senderUserId==targetId " style="padding-left: 30rpx;display: flex;flex-direction: column;">
								<view style="display: flex;justify-content: flex-start;align-items: center;padding: 30rpx;">
									 <text style="font-size: 24rpx;color: #272832;">{{toTime(item.sentTime)}}</text> 
								</view>
								<view style="display: flex;flex-direction: row;justify-content: flex-start;margin-bottom: 15rpx;">
									<view
										style="display: flex;flex-direction: column;align-items: center;justify-content: flex-start;">
										<image style="width: 80rpx;height: 80rpx;border-radius: 50%"
											:src="info.icon" ></image>
										<!-- <text
											style="text-align: center;font-size: 24rpx;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: rgba(39, 40, 50, 1);">{{storename}}</text> -->
									</view>
									<view
										style="position: relative;margin-left: 50rpx;margin-right: 100rpx;background: rgba(255, 255, 255, 1);border-radius: 20rpx;padding: 20rpx;">
										<text v-if="!item.msg.src" class="user-text" style="font-size: 26rpx;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: rgba(39, 40, 50, 1);">{{item.msg.content}}</text>
										<img v-if="item.msg.src" @click="onLookBigImage(item.msg.src)" :src="item.msg.src" style="width: 200rpx;height: 200rpx;" alt="">
									</view>
								</view>
							</view>
						</view>
					</view>
					<view>
						<view>
							<!-- 我发送 -->
							<view
							v-if="item.msg.senderUserId == memberId && item.msg.targetId==targetId"
							class="myCon">
								<!-- 时间框 -->
								<view class="times">
									 <text class="timeCon">{{ toTime(item.sentTime)}}</text> 
								</view>
								<!-- 聊天消息框 -->
								<view class="chat-big">
									<!-- 头像框 -->
									<view class="avatar">
										<image :src="userinfo.messageLogo"></image>
										<!-- <text style="text-align: center;font-size: 24rpx;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: rgba(39, 40, 50, 1);">{{userinfo.mobile}}</text> -->
									</view>
									<!-- 消息框 -->
									<view class="chat-content" >
										<!-- 三角 -->
										<view class="chat-jiao" ></view>
										<!-- 聊天内容 -->
										<text v-if="!item.msg.src" class="chat-body" >{{item.msg.content}}</text>
										<!-- <text v-if="!item.msg.src" class="user-text" style="font-size: 26rpx;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: rgba(39, 40, 50, 1);">{{item.msg.content}}</text> -->
										<img v-if="item.msg.src" @click="onLookBigImage(item.msg.src)" :src="item.msg.src" style="width: 200rpx;height: 200rpx;" alt="">
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
		</scroll-view>
		<!-- 聊天input框 -->
		<view style="position: fixed;
		bottom: 0rpx;
		display: flex;
		width: 100%;
		flex-direction: row;
		height: 140rpx;
		background: #FFFFFF;box-shadow: 0px 1px 0px 0px rgba(0, 0, 0, 0.1);"
		:style="{bottom: inputHeight}"
		>
			<view style="padding-left: 12rpx;
			padding-right: 12rpx;
			display: flex;
			align-items: center;">
				<!-- <image src="/static/image/index/yuyin.png"></image> -->
			</view>
			<view class="input-box">
				<input
				id="input"
				style="width: 600rpx;
				height: 72rpx;
				margin-top: 10rpx;
				background: #f7f7f7;
				border-radius: 10rpx;"
				type="text"
				value=""
				v-model="words"
				:focus="focus"
				:adjust-position="false"
				:confirm-hold="true"
				 :enableNative="false"
				@focus="inputBindFocus"
				@blur="inputBindBlur"
				@confirm="sendPravte"
				confirm-type="send"
				placeholder="请输入发送的内容"
				 />
			</view>
			<view style="width: 188rpx;
			display: flex;
			
			justify-content: space-evenly;margin-top: 20rpx;"
			>
				<!--	 <image src="/static/image/index/biaoqin.png"></image>
			<image src="/static/image/index/add.png"></image> -->
			<image style="	width: 56rpx;
			height: 56rpx;" src="https://image.hzwltb69.com/app/images/kfpic.png" @click="sendImageMessage"></image>
				<image style="	width: 56rpx;
				height: 56rpx;" src="https://image.hzwltb69.com/app/images/send.png"
				 @click="sendPravte"></image>
				<!-- <button @click="sendPravte">发送</button>-->
			</view>
		</view>
	</view>
	</view>
</template>

<script>
import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
	//ryGlobalData是全局，去main.js
	export default {
		data() {
			return {
				title: 'Hello',
				msgList: [],
				textMsg: '',
				words: '',
				name: '',
				img: '',
				storeId: "",
				logo: '',
				userinfo: uni.getStorageSync("userinfo"),
				UID: uni.getStorageSync("UId"),
				targetId: "",
				storename: "",
				memberId:"",
				resultList:"",
				info: {
					name: '69商城客服',
					icon: 'https://image.hzwltb69.com/upload/common/admin.png'
				},
				childrenId: "id-19",
				inputHeight: '0rpx',
				scrollTop: 10,
				// 下顶标准值为 140rpx
				height: "140rpx",
				focus: false,
				old: {
				scrollTop: 0
				 }
			}
		},
		onLoad(e) {
			//连接融云
			this.logo = "https://image.hzwltb69.com/app/images/customerser.png";
			this.storename = "平台客服";
			this.targetId ="admin3010"
					
		 
			this.memberId = "member"+uni.getStorageSync("UId")
		  
			this.name = this.userinfo.name
 
			this.connectRy();
		},
		methods: {
			// 浏览大图
			onLookBigImage(e){
				console.log(e);
				uni.previewImage({
					urls:[e]
				})
			},
			// 键盘弹出
			inputBindFocus(e){
				let that = this
				that.height = parseInt(e.detail.height) + parseInt(that.height)
				that.height = that.height + 'px'
				that.inputHeight = e.detail.height + 'px'
				that.goEnd()
			},
			// 键盘隐藏
			inputBindBlur(){
				let that = this
				that.height = '140rpx'
				that.inputHeight = 0 + 'rpx'
				console.log(that.height);
			},
			connectRy() {
				//判断是否连接，连接了直接获取聊天列表
				if (this.ryGlobalData.ryStatus.status !== 99) {
					this.getMsgList()
					return
				}
				
				let that = this;
				let token = ""
				//uni.showLoading({})
				that.$http(
					'common.rongyun', {
						memberId: uni.getStorageSync("UId"),
						refresh: false
					},
				).then(res => {

					if (res.code == 200) {
						token = res.token;
					    this.ryConnet(token)
					}
				});
					 
				   //this.ryConnet()		 
			},
			ryConnet(token) { // 连接
				var im = this.ryGlobalData.ryStatus.RongIMLib
				let _t = this
				//token，去找后台要，不给就锤他
				let ry_token = token
				//let ry_token="hwqrppVQNicng1peuiTz9JGeaCBDOoa2MKx0svgqBPA=@dxbv.cn.rongnav.com;dxbv.cn.rongcfg.com"
				im.connect(token).then((user) => {
					// 开启监听回调 接收消息
					const Events = im.Events
					const listener = (evt) => {
					  console.log(evt.messages,'监听消息回调')
					  let message = evt.messages[0]
					  if(evt.messages[0].content.imageUri){
						  console.log('存在图片',evt.messages[0].content.imageUri);
					  }
					  let obj = {
					  	// type: message.data.type,
					  	messageType: message.messageType,
					  	sentTime: message.sentTime,
					  	msg: {
					  		targetId: message.targetId,
					  		senderUserId: message.senderUserId,
					  		content: message.content.content,
							src: evt.messages[0].content.imageUri ? evt.messages[0].content.imageUri : ''
					  	}
					  }
					  _t.msgList.push(obj)
					  _t.goEnd()
					};
					im.addEventListener(Events.MESSAGES, listener)
					_t.getHistoryMsgList()
				}).catch(function(error) {
					
				});
			},
			setmsg(v){
				    let _t = this
				
					let obj = {
						type: v.message.type,
						messageType: v.message.messageType,
						sentTime: v.message.sentTime,
						msg: {
							targetId: v.message.targetId,
							senderUserId: v.message.senderUserId,
							content: v.message.content.content,
							imageUri: v.message.content.imageUri || ''
						},
						
					}
					_t.msgList.push(obj)
					
			},
			// getMsgList() { //获取列表
			// 	let _t = this
			// 	//id，去找后台要，不给就锤他
			// 	let ry_service_uid = this.targetId
			// 	const im = this.ryGlobalData.ryStatus.im
			
			// 	const RongIMLib = this.ryGlobalData.ryStatus.RongIMLib
			// 	var conversation = im.Conversation.get({
			// 		targetId: ry_service_uid,
			// 		type: RongIMLib.CONVERSATION_TYPE.PRIVATE
			// 	});
			// 	var option = {
			// 		timestrap: +new Date(),
			// 		count: 20
			// 	};
			// 	conversation.getMessages(option).then(function(result) {
			// 		var list = result.list; // 历史消息列表
			// 		let arr = []
					 
			// 		if (list.length > 0) {
					 
			// 			list.forEach((v, k) => {
			// 				let obj = {
			// 					type: v.type,
			// 					messageType: v.messageType,
			// 					sentTime: v.sentTime,
			// 					msg: {
			// 						targetId: v.targetId,
			// 						senderUserId: v.senderUserId,
			// 						content: v.content.content,
			// 						imageUri: v.content.imageUri || ''
			// 					}
			// 				}
			// 				arr.push(obj)
			// 			})
			// 		}
			// 		_t.msgList = arr
				  
			// 		if(arr[arr.length - 1].msg.imageUri.fromId == `member${_t.UID}`){
			// 			_t.info.name =  arr[arr.length - 1].msg.imageUri.name
			// 			_t.info.icon =  arr[arr.length - 1].msg.imageUri.icon
					 
			// 		}else{
			// 			_t.info.name =  arr[arr.length - 1].msg.imageUri.nickname
			// 			_t.info.icon =  arr[arr.length - 1].msg.imageUri.avatar
					 
			// 		}
			// 		uni.setNavigationBarTitle({
			// 			title:_t.info.name
			// 		})
			// 		_t.goEnd()
			// 		// _t.$nextTick(function() {
			// 		// 	// 滚动到底
			// 		// 	if (arr.length > 0) {
			// 		// 		_t.scrollToView = 'msg' + arr[arr.length - 1].sentTime
			// 		// 	}
			// 		// });

			// 	});
			// },
			getHistoryMsgList() { //获取历史消息列表
				let _t = this
				//id，去找后台要，不给就锤他
				let ry_service_uid = this.targetId
				
				// 融云实例
				const RongIMLib = this.ryGlobalData.ryStatus.RongIMLib
				// 查询参数1
				var conversation = {
					targetId: ry_service_uid,
					conversationType: RongIMLib.ConversationType.PRIVATE
				};
				// 查询时间参数
				var option = {
					    timestamp: 0,
					    count: 20,
					    order: 0
				};
				RongIMLib.getHistoryMessages(conversation, option).then(function(result) {
					var list = result.data.list; // 历史消息列表
					let arr = []
					if (list.length > 0) {
			
						list.forEach((v, k) => {
							let obj = {
								type: v.type,
								messageType: v.messageType,
								sentTime: v.sentTime,
								msg: {
									targetId: v.targetId,
									senderUserId: v.senderUserId,
									content: v.content.content,
									extra: v.content.extra || '',
									src: v.content.imageUri ? v.content.imageUri : ''
								}
							}
							arr.push(obj)
						})
					}
					_t.msgList = arr
					_t.goEnd()
					console.log(arr[arr.length - 1]);
					if(arr[arr.length - 1].msg.senderUserId == `member${_t.UID}`){
						_t.info.name =  arr[arr.length - 1].msg.extra.name
						_t.info.icon =  arr[arr.length - 1].msg.extra.icon
						console.log(_t.info,'我发的，info');
					}else{
						_t.info.name =  arr[arr.length - 1].msg.extra.nickname
						_t.info.icon =  arr[arr.length - 1].msg.extra.avatar
						console.log(_t.info,'对方的，info');
					}
					uni.setNavigationBarTitle({
						title:_t.info.name
					})
					// 清除未读
					const conversationType = RongIMLib.ConversationType.PRIVATE;
					const targetId = ry_service_uid;
					RongIMLib.clearMessagesUnreadStatus({
						conversationType,
						targetId
					}).then(res => {
					  if (res.code === 0) {
					    console.log(res.code,res)
					  } else {
					    console.log(res.code, res.msg)
					  }
					})
				});
			},
			// 点击发送
			sendPravte() {
				// return
				//this.hideDrawer();//隐藏抽屉
				this.textMsg = this.words;//清空输入框
				if (!this.textMsg) {
					return;
				}
				// let content = this.replaceEmoji(this.textMsg);
				// let msg = {text:content}
				let msg = this.textMsg
				this.sendMsg(msg, 'text');
				this.textMsg =""
				this.words=""
			},
			// 发送消息 => 图片消息
			sendImageMessage(){
				let that = this
				uni.chooseImage({
					count: 1,
					success(e) {
						uni.uploadFile({
							url: 'https://www.hzwltb69.com/api/common/file/uploadFolderImage',
							filePath: e.tempFilePaths[0],
							file: e.tempFiles[0],
							name: 'file',
							formData:{
								imageType: 'SOURCE',
								imageUploadPath: 'rong'
							},
							success(e) {
								let src = JSON.parse(e.data).url
								that.sendImg(src)
							}
						})
					}
				})
				
			},
			onBlur(){
				this.focus = false
				this.inputBindBlur()
			},
			sendImg(e){
				console.log('执行',e);
				let file = e
				let _t = this
				let ry_service_uid = this.targetId
				// 配置融云参数
				const RongIMLib = this.ryGlobalData.ryStatus.RongIMLib
				var conversation = {
					targetId: ry_service_uid,
					conversationType: RongIMLib.ConversationType.PRIVATE,
				};
				// //文件列表
				// const msgBody = {
				//   file, // 待上传文件
				//   extra: {
				//   	nickname: uni.getStorageSync("userinfo") .mobile,
				//   	avatar: uni.getStorageSync("userinfo").avatar,
				//   	fromId: `member${_t.userinfo.id}`,
				//   	toId: _t.targetId,
				//   	name: _t.info.name,
				//   	icon: _t.info.icon
				//   }
				// }
				// // 回调
				// const hooks = {
				//   onProgress (progress) {
				// 	  console.log(progress);
				//   },  // 上传进度监听，可选
				//   onComplete (fileInfo) { // 上传完成时的回调钩子，可选
				//   console.log('上传完成了======================');
				//     console.log(fileInfo.url) // 文件存储地址
				//     // 如果需要构建自定义消息，return new ABCMesssage('')
				//     // ABCMesssage 定义通过自定义消息实现 `const ABCMesssage = RongIMLib.registerMessageType(...)`
				//     // 无 return 返回值的情况下，SDK 默认发送 FileMessage
				//   }
				// }
				
				// 图片内容
				const message = new RongIMLib.ImageMessage(
				{ 
				content: '',
				imageUri:e,
				extra: {
					nickname: uni.getStorageSync("userinfo") .mobile,
					avatar: uni.getStorageSync("userinfo").avatar,
					fromId: `member${_t.userinfo.id}`,
					toId: _t.targetId,
					name: _t.info.name,
					icon: _t.info.icon
				}
				})
				// 回调
				const options = {
					  // 如果需要发送 @ 消息，isMentioned 需设置为 true
					  isMentioned: false,
					  // 消息发送前的回调，可以使用此回调返回的 message 用于列表渲染
					  onSendBefore: (message) => {
					    console.log('消息发送前的回调', message)
					  }
				}
				// 发送
				RongIMLib.sendMessage(
				  conversation,
				  message,
				  options,
				).then( message => {
					if(message.code == RongIMLib.ErrorCode.SUCCESS){
						// 我发送的图片消息回显
						let obj = {
							// type: message.data.type,
							messageType: message.data.messageType,
							sentTime: message.data.sentTime,
							msg: {
								targetId: message.data.targetId,
								senderUserId: message.data.senderUserId,
								content: message.data.content.content,
								src: message.data.content.imageUri ? message.data.content.imageUri : ''
							}
						}
						_t.msgList.push(obj)
						_t.goEnd()
					}
					
				})
			},
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			// 发送消息 => 简单文字消息
			sendMsg(contentVal, type) {
				let _t = this
				let ry_service_uid = this.targetId
				const RongIMLib = this.ryGlobalData.ryStatus.RongIMLib
				var conversation = {
					targetId: ry_service_uid,
					conversationType: RongIMLib.ConversationType.PRIVATE,
				};
				const message = new RongIMLib.TextMessage({
					content: contentVal,
					extra: {
						nickname: uni.getStorageSync("userinfo") .mobile,
						avatar: uni.getStorageSync("userinfo").avatar,
						fromId: `member${_t.userinfo.id}`,
						toId: _t.targetId,
						name: _t.info.name,
						icon: _t.info.icon
					}
				})
				const options = {
					  // 如果需要发送 @ 消息，isMentioned 需设置为 true
					  isMentioned: false,
					  // 消息发送前的回调，可以使用此回调返回的 message 用于列表渲染
					  onSendBefore: (message) => {
					    console.log('消息发送前的回调', message)
					  }
				}
				RongIMLib.sendMessage(conversation,message,options).then(function(message) {
					console.log(message);
					if(message.code == RongIMLib.ErrorCode.SUCCESS){
						let obj = {
							type: message.data.type,
							messageType: message.data.messageType,
							sentTime: message.data.sentTime,
							msg: {
								targetId: message.data.targetId,
								senderUserId: message.data.senderUserId,
								content: message.data.content.content,
							}
						}
						_t.msgList.push(obj)
						_t.goEnd()
					}
				}, err => {
					console.log(err, 'err')
				});
			},
			  handleScrollBottom() {
			      this.$nextTick(() => {
			        let scrollElem = this.$refs.scrollDiv;
			        scrollElem.scrollTo({ top: scrollElem .scrollHeight, behavior: 'smooth' });
			      });
			    },
				toTime(time){
					 var date = new Date(time);
					  var Y = date.getFullYear() + "-";
					  var M =
					    (date.getMonth() + 1 < 10
					      ? "0" + (date.getMonth() + 1)
					      : date.getMonth() + 1) + "-";
					  var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
					  var h = date.getHours() + ":";
					  var m = date.getMinutes() + ":";
					  var s = date.getSeconds();
				  return Y + M + D + h + m + s;
				},
				scroll(e) {
					console.log(e.detail.scrollTop,'e===========================');
				this.old.scrollTop = e.detail.scrollTop
				// 如果是通过点击input弹出的软键盘 滑动时隐藏掉软键盘
				},
				goEnd(){
						this.scrollTop = this.old.scrollTop
									this.$nextTick(function() {
										this.scrollTop = 9999999999
									});
				}
		},
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: f1f1f1;
	}
	.user-text:before {
		position: absolute;
		content: "\00a0";
		width: 0rpx;
		height: 0rpx;
		border-width: 16rpx 36rpx 16rpx 0;
		border-style: solid;
		border-color: transparent #FFFFFF transparent transparent;
		top: 30rpx;
		left: -36rpx;
	}
	// 我发的消息
	.myCon{
		padding-left: 30rpx;
		display: flex;
		flex-direction: column;
		.times{
			display: flex;
			// justify-content: center;
			justify-content: flex-end;
			align-items: center;
			padding: 30rpx;
			.timeCon{
				font-size: 24rpx;
				color: #272832;
			}
		}
		.chat-big{
			display: flex;
			flex-direction: row-reverse;
			justify-content: flex-start;
			margin-bottom: 15rpx;
		}
		.avatar{
			padding: 10rpx;
			display: flex;
			flex-direction: column;
			justify-content: flex-start;
			align-items: center;
			image{
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%
			}
		}
		.chat-content{
			position: relative;
			display: flex;
			align-items: center;
			margin-left: 100rpx;
			margin-right: 20rpx;
			border-radius: 20rpx;
			padding: 10rpx;
			// color: #000;
			background: #518cff;
			padding-left: 20rpx;
			padding-right: 20rpx;
			color: #fff;
			.chat-jiao{
				position: absolute;
				display: inline-block;
				top: 30rpx;
				width: 0rpx;
				height: 0rpx;
				border-width: 16rpx 0rpx 16rpx 26rpx;
				right: -26rpx;
				border-style: solid;
				border-color: transparent transparent transparent #518cff;
			}
			.chat-body{
				font-size: 28rpx;
				font-family: PingFangSC-Regular,
				 PingFang SC;font-weight: 400;
				 line-height: 30rpx;
			}
		}
	}
    // 对方消息
	
</style>